package handler

import (
	"github.com/gin-gonic/gin"
	"image-text-mgr/models"
	"net/http"
	"strconv"
)

func Images(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	data := models.Images{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offest := (page - 1) * size
	var img []models.Images
	err := models.DB.Debug().Offset(offest).Limit(size).Find(&img).Error
	var total int64
	models.DB.Model(&models.Images{}).Count(&total)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "展示失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":  200,
			"msg":   "展示成功",
			"data":  img,
			"count": total,
		})
		return
	}
}
